<template>
  <a-upload
    v-model:fileList="fileList"
    list-type="picture-card"
    action="/pc/common/upload"
    image-preview
    @before-remove="handleBeforeRemove"
    @success="handleSuccess"
  />
</template>

<script setup>
  import { ref, nextTick, watch, computed, watchEffect } from 'vue';

  const emits = defineEmits(['update:modelValue']);
  const props = defineProps({
    modelValue: {
      type: String,
      default: ``,
    },
  });

  const getFileList = (modelValue) =>
    modelValue
      ? modelValue.split(',').map((item, index) => ({
          uid: index,
          url: item,
          response: { code: 1, data: { fullurl: item } },
        }))
      : [];

  const getPath = (newFileList) =>
    newFileList
      .filter((item) => item.response)
      .map((item) => item.response.data.fullurl)
      .join(',');

  const fileList = ref(getFileList(props.modelValue));

  watchEffect(async () => {
    await nextTick();
    fileList.value = getFileList(props.modelValue);
  });

  const handleSuccess = async (fileItem) => {
    console.log(fileItem);
    if (fileItem.status !== 'done') return;
    await nextTick();
    emits('update:modelValue', getPath(fileList.value));
  };
  // const handleChange = async (fileList) => {
  //   emits('update:modelValue', getPath(fileList));
  // };
  const handleBeforeRemove = (fileItem) => {
    const index = fileList.value.findIndex((item) => item.uid === fileItem.uid);
    fileList.value.splice(index, 1);
    emits('update:modelValue', getPath(fileList.value));
  };
</script>
<style>
  .arco-table-container .arco-upload-picture-card,
  .arco-table-container .arco-upload-picture-card .arco-upload-list-picture {
    min-width: 55px;
    height: 55px;
    width: 55px;
  }
</style>
